/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Cliente;


import Servidor.ChatMessage;
import java.net.*;
import java.io.*;
import java.util.*;


public class Client  {

	
	private ObjectInputStream sInput;		// to read from the socket
	private ObjectOutputStream sOutput;		// to write on the socket
	private Socket socket;
        private  VentanaCliente cg;
        
	private String server, username;
	private int port;

	
	public Client(String server, int port, String username) {
		
		this(server, port, username, null);
	}

	
	public Client(String server, int port, String username, VentanaCliente cg) {
		this.server = server;
		this.port = port;
		this.username = username;
		this.cg = cg;
	}
	
	public boolean start() {
            
		try {
			socket = new Socket(server, port);
		} 
                
		catch(Exception ec) {
			display("Error conectandose a server:" + ec);
			return false;
		}
		
		String msg = "Conexión aceptada " + socket.getInetAddress() + ":" + socket.getPort();
		display(msg);
	
                
		try
		{
			sInput  = new ObjectInputStream(socket.getInputStream());
			sOutput = new ObjectOutputStream(socket.getOutputStream());
		}
		catch (IOException eIO) {
			display("Exception creando new Input/output Streams: " + eIO);
			return false;
		}

		new ListenFromServer().start();
		try
		{
			sOutput.writeObject(username);
		}
		catch (IOException eIO) {
			display("Exception haciendo login : " + eIO);
			disconnect();
			return false;
		}
		
		return true;
	}

        
	private void display(String msg) {
		if(cg == null)
			System.out.println(msg);   
		else
			cg.mostrarMensaje(msg + "\n"); 		 
	}
	
        
	public void sendMessage(ChatMessage msg) {
		try {
			sOutput.writeObject(msg);
		}
		catch(IOException e) {
			display("Exception escribiendo a server: " + e);
		}
	}

        
	private void disconnect() {
		try { 
			if(sInput != null) sInput.close();
		}
		catch(Exception e) {} 
		try {
			if(sOutput != null) sOutput.close();
		}
		catch(Exception e) {} 
        try{
			if(socket != null) socket.close();
		}
		catch(Exception e) {} 
		
		
		if(cg != null)
			cg.connectionFailed();
			
	}
	
	

	
        
	class ListenFromServer extends Thread {

		public void run() {
			while(true) {
				try {
					String msg = (String) sInput.readObject();
					
                                        if(cg == null) {
						System.out.println(msg);
						System.out.print("> ");
					}
					else {
						cg.mostrarMensaje(msg);
					}
				}
				catch(IOException e) {
					display("Server has close the connection: ");
					if(cg != null) 
						cg.connectionFailed();
					break;
				}
				
                                catch(ClassNotFoundException e2) {
				}
			}
		}
	}
}


